const DataLoader = require('dataloader')
import { sequelize, Task, Progress, Answer } from '../../models'
import { groupData, placeData } from '../../lib/graphql'

export const taskLoader = () =>
  new DataLoader(
    async keys => {
      let data = await Task.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const taskLoaderByDocument = () =>
  new DataLoader(
    async keys => {
      const data = await Task.findAll({
        where: { documentId: { $in: keys } },
        order: [['updatedAt', 'DESC']]
      })

      return groupData(keys, data, 'documentId')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const unreadCountLoaderByTask = () =>
  new DataLoader(
    async keys => {
      const data = await Progress.findAll({
        group: ['taskId'],
        attributes: [
          'taskId',
          [sequelize.fn('COUNT', 'taskId'), 'unreadCount']
        ],
        where: { taskId: { $in: keys }, unreadCount: 1 }
      })
      // pull finishCount from dataValues
      for (let i in data) {
        data[i].unreadCount = data[i].dataValues.unreadCount
      }

      return placeData(keys, data, 'taskId', 0, 'unreadCount')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const finishCountLoaderByTask = () =>
  new DataLoader(
    async keys => {
      const data = await Progress.findAll({
        group: ['taskId'],
        attributes: [
          'taskId',
          [sequelize.fn('COUNT', 'taskId'), 'finishCount']
        ],
        where: { taskId: { $in: keys }, state: { $ne: 'start' } }
      })
      // pull finishCount from dataValues
      for (let i in data) {
        data[i].finishCount = data[i].dataValues.finishCount
      }

      return placeData(keys, data, 'taskId', 0, 'finishCount')
    },
    { cacheKeyFn: key => key.toString() }
  )
